/**
 * Created by Listen on 17/2/16.
 * http配置
 */
import axios from 'axios'
import router from './router'

// axios 配置
axios.defaults.timeout = 10000;
axios.defaults.baseURL = process.env.API_ROOT; //方法一：获取生产或开发环境配置的URL地址
// axios.defaults.baseURL = 'http://shop.sixsea.cn/api'; //方法二：生产或开发环境可以直接配置跨域地址，调用`/xxx`
// axios.defaults.baseURL = process.env.VUE_APP_URL; //可能失效

// http request 拦截器
axios.interceptors.request.use(
   config => {
      if (localStorage.token) {
         config.headers.Authorization = `Bearer ${localStorage.token}`;
      }
      return config;
   },
   err => {
      return Promise.reject(err);
   });

// http response 拦截器
axios.interceptors.response.use(
   response => {
      return response;
   },
   error => {
      if (error.response) {
         switch (error.response.status) {
            case 400:
               // localStorage.removeItem('token')
               // 401 清除token信息并跳转到登录页面
               router.replace({
                  path: 'login',
                  query: {redirect: router.currentRoute.fullPath}
               })
         }
      }
      // console.log(JSON.stringify(error));//console : Error: Request failed with status code 402
      return Promise.reject(error.response.data)
   });

export default axios;
